{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load medical images\n",
    "\n",
    "This notebook describes how to easily load different formats of medical images in MONAI and execute additional image transforms.\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Project-MONAI/tutorials/blob/master/modules/load_medical_images.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup environment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:00.722456Z",
     "iopub.status.busy": "2021-01-14T12:34:00.721912Z",
     "iopub.status.idle": "2021-01-14T12:34:04.902827Z",
     "shell.execute_reply": "2021-01-14T12:34:04.902170Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "!python -c \"import monai\" || pip install -q \"monai-weekly[itk, pillow]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:04.909819Z",
     "iopub.status.busy": "2021-01-14T12:34:04.909227Z",
     "iopub.status.idle": "2021-01-14T12:34:07.526324Z",
     "shell.execute_reply": "2021-01-14T12:34:07.524953Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MONAI version: 0.6.0+22.g027947bf.dirty\n",
      "Numpy version: 1.21.0\n",
      "Pytorch version: 1.9.0\n",
      "MONAI flags: HAS_EXT = False, USE_COMPILED = False\n",
      "MONAI rev id: 027947bf91ff0dfac94f472ed1855cd49e3feb8d\n",
      "\n",
      "Optional dependencies:\n",
      "Pytorch Ignite version: 0.4.5\n",
      "Nibabel version: 3.2.1\n",
      "scikit-image version: 0.18.2\n",
      "Pillow version: 8.2.0\n",
      "Tensorboard version: 2.4.1\n",
      "gdown version: 3.13.0\n",
      "TorchVision version: 0.10.0\n",
      "tqdm version: 4.61.1\n",
      "lmdb version: 1.2.1\n",
      "psutil version: 5.8.0\n",
      "pandas version: 1.1.5\n",
      "einops version: 0.3.0\n",
      "\n",
      "For details about installing the optional dependencies, please visit:\n",
      "    https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Copyright 2020 MONAI Consortium\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\n",
    "# Copyright 2020 MONAI Consortium\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\n",
    "import os\n",
    "import shutil\n",
    "import numpy as np\n",
    "import itk\n",
    "from PIL import Image\n",
    "import tempfile\n",
    "from monai.data import ITKReader, PILReader\n",
    "from monai.transforms import (\n",
    "    LoadImage, LoadImaged, EnsureChannelFirstd,\n",
    "    Resized, EnsureTyped, Compose\n",
    ")\n",
    "from monai.config import print_config\n",
    "\n",
    "print_config()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load Nifti image with default image reader\n",
    "MONAI automatically choose readers based on the supported suffixes and in below order:\n",
    "- User specified reader at runtime when call this loader.\n",
    "- Registered readers from the latest to the first in list.\n",
    "- Default readers: (nii, nii.gz -> NibabelReader), (png, jpg, bmp -> PILReader),\n",
    "  (npz, npy -> NumpyReader), (others -> ITKReader)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Generate an example image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# generate 3D test images\n",
    "tempdir = tempfile.mkdtemp()\n",
    "test_image = np.random.rand(64, 128, 96)\n",
    "filename = os.path.join(tempdir, \"test_image.nii.gz\")\n",
    "itk_np_view = itk.image_view_from_array(test_image)\n",
    "itk.imwrite(itk_np_view, filename)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load the image file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:07.530773Z",
     "iopub.status.busy": "2021-01-14T12:34:07.530335Z",
     "iopub.status.idle": "2021-01-14T12:34:08.080092Z",
     "shell.execute_reply": "2021-01-14T12:34:08.080424Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image data shape:(96, 128, 64)\n",
      "meta data:{'sizeof_hdr': array(348, dtype=int32), 'extents': array(0, dtype=int32), 'session_error': array(0, dtype=int16), 'dim_info': array(0, dtype=uint8), 'dim': array([  3,  96, 128,  64,   1,   1,   1,   1], dtype=int16), 'intent_p1': array(0., dtype=float32), 'intent_p2': array(0., dtype=float32), 'intent_p3': array(0., dtype=float32), 'intent_code': array(0, dtype=int16), 'datatype': array(64, dtype=int16), 'bitpix': array(64, dtype=int16), 'slice_start': array(0, dtype=int16), 'pixdim': array([1., 1., 1., 1., 0., 0., 0., 0.], dtype=float32), 'vox_offset': array(0., dtype=float32), 'scl_slope': array(nan, dtype=float32), 'scl_inter': array(nan, dtype=float32), 'slice_end': array(0, dtype=int16), 'slice_code': array(0, dtype=uint8), 'xyzt_units': array(2, dtype=uint8), 'cal_max': array(0., dtype=float32), 'cal_min': array(0., dtype=float32), 'slice_duration': array(0., dtype=float32), 'toffset': array(0., dtype=float32), 'glmax': array(0, dtype=int32), 'glmin': array(0, dtype=int32), 'qform_code': array(1, dtype=int16), 'sform_code': array(1, dtype=int16), 'quatern_b': array(0., dtype=float32), 'quatern_c': array(0., dtype=float32), 'quatern_d': array(1., dtype=float32), 'qoffset_x': array(-0., dtype=float32), 'qoffset_y': array(-0., dtype=float32), 'qoffset_z': array(0., dtype=float32), 'srow_x': array([-1.,  0.,  0., -0.], dtype=float32), 'srow_y': array([ 0., -1.,  0., -0.], dtype=float32), 'srow_z': array([0., 0., 1., 0.], dtype=float32), 'affine': array([[-1.,  0.,  0., -0.],\n",
      "       [ 0., -1.,  0., -0.],\n",
      "       [ 0.,  0.,  1.,  0.],\n",
      "       [ 0.,  0.,  0.,  1.]]), 'original_affine': array([[-1.,  0.,  0., -0.],\n",
      "       [ 0., -1.,  0., -0.],\n",
      "       [ 0.,  0.,  1.,  0.],\n",
      "       [ 0.,  0.,  0.,  1.]]), 'as_closest_canonical': False, 'spatial_shape': array([ 96, 128,  64], dtype=int16), 'original_channel_dim': 'no_channel', 'filename_or_obj': '/var/folders/6f/fdkl7m0x7sz3nj_t7p3ccgz00000gp/T/tmpq2arvyex/test_image.nii.gz'}\n"
     ]
    }
   ],
   "source": [
    "data, meta = LoadImage()(filename)\n",
    "print(f\"image data shape:{data.shape}\")\n",
    "print(f\"meta data:{meta}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load a list of Nifti images and stack them as a multi-channel image\n",
    "Loading a list of files, stack them together and add a new dimension as first dimension.\n",
    "\n",
    "And use the meta data of the first image to represent the stacked result."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Generate some image examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:09.002685Z",
     "iopub.status.busy": "2021-01-14T12:34:09.002010Z",
     "iopub.status.idle": "2021-01-14T12:34:09.184221Z",
     "shell.execute_reply": "2021-01-14T12:34:09.184551Z"
    }
   },
   "outputs": [],
   "source": [
    "filenames = [\"test_image.nii.gz\", \"test_image2.nii.gz\", \"test_image3.nii.gz\"]\n",
    "for i, name in enumerate(filenames):\n",
    "    filenames[i] = os.path.join(tempdir, name)\n",
    "    itk_np_view = itk.image_view_from_array(test_image)\n",
    "    itk.imwrite(itk_np_view, filenames[i])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load the images\n",
    "Note that the output data shape is (3, 96, 128, 64), indicating a three-channel image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image data shape:(3, 96, 128, 64)\n",
      "meta data:{'sizeof_hdr': array(348, dtype=int32), 'extents': array(0, dtype=int32), 'session_error': array(0, dtype=int16), 'dim_info': array(0, dtype=uint8), 'dim': array([  3,  96, 128,  64,   1,   1,   1,   1], dtype=int16), 'intent_p1': array(0., dtype=float32), 'intent_p2': array(0., dtype=float32), 'intent_p3': array(0., dtype=float32), 'intent_code': array(0, dtype=int16), 'datatype': array(64, dtype=int16), 'bitpix': array(64, dtype=int16), 'slice_start': array(0, dtype=int16), 'pixdim': array([1., 1., 1., 1., 0., 0., 0., 0.], dtype=float32), 'vox_offset': array(0., dtype=float32), 'scl_slope': array(nan, dtype=float32), 'scl_inter': array(nan, dtype=float32), 'slice_end': array(0, dtype=int16), 'slice_code': array(0, dtype=uint8), 'xyzt_units': array(2, dtype=uint8), 'cal_max': array(0., dtype=float32), 'cal_min': array(0., dtype=float32), 'slice_duration': array(0., dtype=float32), 'toffset': array(0., dtype=float32), 'glmax': array(0, dtype=int32), 'glmin': array(0, dtype=int32), 'qform_code': array(1, dtype=int16), 'sform_code': array(1, dtype=int16), 'quatern_b': array(0., dtype=float32), 'quatern_c': array(0., dtype=float32), 'quatern_d': array(1., dtype=float32), 'qoffset_x': array(-0., dtype=float32), 'qoffset_y': array(-0., dtype=float32), 'qoffset_z': array(0., dtype=float32), 'srow_x': array([-1.,  0.,  0., -0.], dtype=float32), 'srow_y': array([ 0., -1.,  0., -0.], dtype=float32), 'srow_z': array([0., 0., 1., 0.], dtype=float32), 'affine': array([[-1.,  0.,  0., -0.],\n",
      "       [ 0., -1.,  0., -0.],\n",
      "       [ 0.,  0.,  1.,  0.],\n",
      "       [ 0.,  0.,  0.,  1.]]), 'original_affine': array([[-1.,  0.,  0., -0.],\n",
      "       [ 0., -1.,  0., -0.],\n",
      "       [ 0.,  0.,  1.,  0.],\n",
      "       [ 0.,  0.,  0.,  1.]]), 'as_closest_canonical': False, 'spatial_shape': array([ 96, 128,  64], dtype=int16), 'original_channel_dim': 0, 'filename_or_obj': '/var/folders/6f/fdkl7m0x7sz3nj_t7p3ccgz00000gp/T/tmpq2arvyex/test_image.nii.gz'}\n"
     ]
    }
   ],
   "source": [
    "data, meta = LoadImage()(filenames)\n",
    "\n",
    "print(f\"image data shape:{data.shape}\")\n",
    "print(f\"meta data:{meta}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load 3D image in DICOM format"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Generate an example image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:09.188846Z",
     "iopub.status.busy": "2021-01-14T12:34:09.188448Z",
     "iopub.status.idle": "2021-01-14T12:34:09.206846Z",
     "shell.execute_reply": "2021-01-14T12:34:09.207174Z"
    }
   },
   "outputs": [],
   "source": [
    "filename = os.path.join(tempdir, \"test_image.dcm\")\n",
    "dcm_image = np.random.randint(256, size=(64, 128, 96)).astype(np.uint8)\n",
    "itk_np_view = itk.image_view_from_array(dcm_image)\n",
    "itk.imwrite(itk_np_view, filename)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load the image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image data shape:(96, 128, 64)\n",
      "meta data:{'0008|0016': '1.2.840.10008.5.1.4.1.1.7.2', '0008|0018': '1.2.826.0.1.3680043.2.1125.1.49144329026051408197861589261117151', '0008|0020': '20210722', '0008|0030': '170636.794924 ', '0008|0050': '', '0008|0060': 'OT', '0008|0090': '', '0010|0010': '', '0010|0020': '', '0010|0030': '', '0010|0040': '', '0020|000d': '1.2.826.0.1.3680043.2.1125.1.55082693700512159103862591206822067', '0020|000e': '1.2.826.0.1.3680043.2.1125.1.88286845929415088271370520342732963', '0020|0010': '', '0020|0011': '', '0020|0013': '', '0020|0052': '1.2.826.0.1.3680043.2.1125.1.54872246537810654209027218359324264', '0028|0002': '1', '0028|0004': 'MONOCHROME2 ', '0028|0008': '64', '0028|0009': '(5200,9230)', '0028|0010': '128', '0028|0011': '96', '0028|0100': '8', '0028|0101': '8', '0028|0102': '7', '0028|0103': '0', '0028|1052': '0 ', '0028|1053': '1 ', '0028|1054': 'US', 'spacing': array([1., 1., 1.]), 'original_affine': array([[-1.,  0.,  0.,  0.],\n",
      "       [ 0., -1.,  0.,  0.],\n",
      "       [ 0.,  0.,  1.,  0.],\n",
      "       [ 0.,  0.,  0.,  1.]]), 'affine': array([[-1.,  0.,  0.,  0.],\n",
      "       [ 0., -1.,  0.,  0.],\n",
      "       [ 0.,  0.,  1.,  0.],\n",
      "       [ 0.,  0.,  0.,  1.]]), 'spatial_shape': array([ 96, 128,  64]), 'original_channel_dim': 'no_channel', 'filename_or_obj': '/var/folders/6f/fdkl7m0x7sz3nj_t7p3ccgz00000gp/T/tmpq2arvyex/test_image.dcm'}\n"
     ]
    }
   ],
   "source": [
    "data, meta = LoadImage()(filename)\n",
    "\n",
    "print(f\"image data shape:{data.shape}\")\n",
    "print(f\"meta data:{meta}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load a list of DICOM images and stack them as a multi-channel image\n",
    "Loading a list of files, stack them together and add a new dimension as first dimension.\n",
    "\n",
    "And use the meta data of the first image to represent the stacked result."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Generate some image examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:09.240561Z",
     "iopub.status.busy": "2021-01-14T12:34:09.240052Z",
     "iopub.status.idle": "2021-01-14T12:34:09.249575Z",
     "shell.execute_reply": "2021-01-14T12:34:09.249908Z"
    }
   },
   "outputs": [],
   "source": [
    "filenames = [\"test_image-1.dcm\", \"test_image-2.dcm\", \"test_image-3.dcm\"]\n",
    "for i, name in enumerate(filenames):\n",
    "    filenames[i] = os.path.join(tempdir, name)\n",
    "    dcm_image = np.random.randint(256, size=(64, 128, 96)).astype(np.uint8)\n",
    "    itk_np_view = itk.image_view_from_array(dcm_image)\n",
    "    itk.imwrite(itk_np_view, filenames[i])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load the images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image data shape:(3, 96, 128, 64)\n",
      "meta data:{'0008|0016': '1.2.840.10008.5.1.4.1.1.7.2', '0008|0018': '1.2.826.0.1.3680043.2.1125.1.70459687821230247148357643462536357', '0008|0020': '20210722', '0008|0030': '170636.830318 ', '0008|0050': '', '0008|0060': 'OT', '0008|0090': '', '0010|0010': '', '0010|0020': '', '0010|0030': '', '0010|0040': '', '0020|000d': '1.2.826.0.1.3680043.2.1125.1.29026801319907695346385092515779097', '0020|000e': '1.2.826.0.1.3680043.2.1125.1.48166663359438709592920991059259631', '0020|0010': '', '0020|0011': '', '0020|0013': '', '0020|0052': '1.2.826.0.1.3680043.2.1125.1.52318595437965660783667062205792724', '0028|0002': '1', '0028|0004': 'MONOCHROME2 ', '0028|0008': '64', '0028|0009': '(5200,9230)', '0028|0010': '128', '0028|0011': '96', '0028|0100': '8', '0028|0101': '8', '0028|0102': '7', '0028|0103': '0', '0028|1052': '0 ', '0028|1053': '1 ', '0028|1054': 'US', 'spacing': array([1., 1., 1.]), 'original_affine': array([[-1.,  0.,  0.,  0.],\n",
      "       [ 0., -1.,  0.,  0.],\n",
      "       [ 0.,  0.,  1.,  0.],\n",
      "       [ 0.,  0.,  0.,  1.]]), 'affine': array([[-1.,  0.,  0.,  0.],\n",
      "       [ 0., -1.,  0.,  0.],\n",
      "       [ 0.,  0.,  1.,  0.],\n",
      "       [ 0.,  0.,  0.,  1.]]), 'spatial_shape': array([ 96, 128,  64]), 'original_channel_dim': 0, 'filename_or_obj': '/var/folders/6f/fdkl7m0x7sz3nj_t7p3ccgz00000gp/T/tmpq2arvyex/test_image-1.dcm'}\n"
     ]
    }
   ],
   "source": [
    "data, meta = LoadImage()(filenames)\n",
    "\n",
    "print(f\"image data shape:{data.shape}\")\n",
    "print(f\"meta data:{meta}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load 2D image in PNG format"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Generate an image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:09.254871Z",
     "iopub.status.busy": "2021-01-14T12:34:09.254439Z",
     "iopub.status.idle": "2021-01-14T12:34:09.267225Z",
     "shell.execute_reply": "2021-01-14T12:34:09.267591Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "test_image = np.random.randint(0, 256, size=[128, 256])\n",
    "filename = os.path.join(tempdir, \"test_image.png\")\n",
    "Image.fromarray(test_image.astype(\"uint8\")).save(filename)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load the image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image data shape:(256, 128)\n",
      "meta data:{'format': 'PNG', 'mode': 'L', 'width': 256, 'height': 128, 'spatial_shape': array([256, 128]), 'original_channel_dim': 'no_channel', 'filename_or_obj': '/var/folders/6f/fdkl7m0x7sz3nj_t7p3ccgz00000gp/T/tmpq2arvyex/test_image.png'}\n"
     ]
    }
   ],
   "source": [
    "data, meta = LoadImage()(filename)\n",
    "\n",
    "print(f\"image data shape:{data.shape}\")\n",
    "print(f\"meta data:{meta}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load image with specified image reader\n",
    "And we can set additional parameters for the image readers, for example, set `c_order_axis_indexing=True` for `ITKReader`, this parameter will pass to ITK `read()` function later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:09.277760Z",
     "iopub.status.busy": "2021-01-14T12:34:09.277257Z",
     "iopub.status.idle": "2021-01-14T12:34:09.279925Z",
     "shell.execute_reply": "2021-01-14T12:34:09.280267Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image data shape:(256, 128)\n",
      "meta data:{'spacing': array([1., 1.]), 'original_affine': array([[-1.,  0.,  0.],\n",
      "       [ 0., -1.,  0.],\n",
      "       [ 0.,  0.,  1.]]), 'affine': array([[-1.,  0.,  0.],\n",
      "       [ 0., -1.,  0.],\n",
      "       [ 0.,  0.,  1.]]), 'spatial_shape': array([256, 128]), 'original_channel_dim': 'no_channel', 'filename_or_obj': '/var/folders/6f/fdkl7m0x7sz3nj_t7p3ccgz00000gp/T/tmpq2arvyex/test_image.png'}\n"
     ]
    }
   ],
   "source": [
    "loader = LoadImage()\n",
    "loader.register(ITKReader())\n",
    "data, meta = loader(filename)\n",
    "\n",
    "print(f\"image data shape:{data.shape}\")\n",
    "print(f\"meta data:{meta}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load image and execute additional operations\n",
    "Some image readers can support additional operations after reading the image from file.\n",
    "\n",
    "For example, we can set a converter for PILReader: `PILReader(converter=lambda image: image.convert(\"LA\"))`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:09.285732Z",
     "iopub.status.busy": "2021-01-14T12:34:09.285334Z",
     "iopub.status.idle": "2021-01-14T12:34:09.290181Z",
     "shell.execute_reply": "2021-01-14T12:34:09.290485Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image data shape:(256, 128, 2)\n",
      "meta data:{'format': None, 'mode': 'LA', 'width': 256, 'height': 128, 'spatial_shape': array([256, 128]), 'original_channel_dim': -1, 'filename_or_obj': '/var/folders/6f/fdkl7m0x7sz3nj_t7p3ccgz00000gp/T/tmpq2arvyex/test_image.png'}\n"
     ]
    }
   ],
   "source": [
    "loader = LoadImage(PILReader(converter=lambda image: image.convert(\"LA\")))\n",
    "data, meta = loader(filename)\n",
    "\n",
    "print(f\"image data shape:{data.shape}\")\n",
    "print(f\"meta data:{meta}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Combine `LoadImage` with other transforms\n",
    "It's very easy to connect `LoadImage` transform with other transforms to construct a transform chain."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:09.298283Z",
     "iopub.status.busy": "2021-01-14T12:34:09.297826Z",
     "iopub.status.idle": "2021-01-14T12:34:09.389726Z",
     "shell.execute_reply": "2021-01-14T12:34:09.390100Z"
    },
    "scrolled": true,
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image data shape:torch.Size([1, 64, 64])\n",
      "meta data:{'format': 'PNG', 'mode': 'L', 'width': 256, 'height': 128, 'spatial_shape': array([256, 128]), 'original_channel_dim': 'no_channel', 'filename_or_obj': '/var/folders/6f/fdkl7m0x7sz3nj_t7p3ccgz00000gp/T/tmpq2arvyex/test_image.png'}\n"
     ]
    }
   ],
   "source": [
    "transform = Compose([\n",
    "    LoadImaged(keys=\"image\"),\n",
    "    EnsureChannelFirstd(keys=\"image\"),\n",
    "    Resized(keys=\"image\", spatial_size=[64, 64]),\n",
    "    EnsureTyped(\"image\"),\n",
    "])\n",
    "test_data = {\"image\": filename}\n",
    "result = transform(test_data)\n",
    "print(f\"image data shape:{result['image'].shape}\")\n",
    "print(f\"meta data:{result['image_meta_dict']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Cleanup data directory\n",
    "\n",
    "Remove directory if a temporary was used."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:09.394901Z",
     "iopub.status.busy": "2021-01-14T12:34:09.394454Z",
     "iopub.status.idle": "2021-01-14T12:34:09.413518Z",
     "shell.execute_reply": "2021-01-14T12:34:09.413090Z"
    }
   },
   "outputs": [],
   "source": [
    "shutil.rmtree(tempdir)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
